{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Event Study"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While Alphalens is a tool designed to evaluate a cross-sectional signal which can be used to rank many securities each day, we can still make use of Alphalens returns analysis functions, a subset of Alphalens, to create a meaningful event study.\n",
    "\n",
    "An event study is a statistical method to assess the impact of a particular event on the value of a stock. In this example we will evalute what happens to stocks whose price fall below 30$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Imports & Settings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:54:55.486341Z",
     "start_time": "2021-04-19T18:54:55.483129Z"
    }
   },
   "source": [
    "import warnings\n",
    "warnings.filterwarnings('ignore')"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:54:56.240797Z",
     "start_time": "2021-04-19T18:54:55.491468Z"
    }
   },
   "source": [
    "import alphalens\n",
    "import pandas as pd"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:54:56.246046Z",
     "start_time": "2021-04-19T18:54:56.242196Z"
    }
   },
   "source": [
    "%matplotlib inline"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Load Data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Below is a simple mapping of tickers to sectors for a universe of 500 large cap stocks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:54:56.260987Z",
     "start_time": "2021-04-19T18:54:56.247691Z"
    }
   },
   "source": [
    "tickers = ['ACN', 'ATVI', 'ADBE', 'AMD', 'AKAM', 'ADS', 'GOOGL', 'GOOG', 'APH', 'ADI', 'ANSS', 'AAPL',\n",
    "           'AVGO', 'CA', 'CDNS', 'CSCO', 'CTXS', 'CTSH', 'GLW', 'CSRA', 'DXC', 'EBAY', 'EA', 'FFIV', 'FB',\n",
    "           'FLIR', 'IT', 'GPN', 'HRS', 'HPE', 'HPQ', 'INTC', 'IBM', 'INTU', 'JNPR', 'KLAC', 'LRCX', 'MA', 'MCHP',\n",
    "           'MSFT', 'MSI', 'NTAP', 'NFLX', 'NVDA', 'ORCL', 'PAYX', 'PYPL', 'QRVO', 'QCOM', 'RHT', 'CRM', 'STX',\n",
    "           'AMG', 'AFL', 'ALL', 'AXP', 'AIG', 'AMP', 'AON', 'AJG', 'AIZ', 'BAC', 'BK', 'BBT', 'BRK.B', 'BLK', 'HRB',\n",
    "           'BHF', 'COF', 'CBOE', 'SCHW', 'CB', 'CINF', 'C', 'CFG', 'CME', 'CMA', 'DFS', 'ETFC', 'RE', 'FITB', 'BEN',\n",
    "           'GS', 'HIG', 'HBAN', 'ICE', 'IVZ', 'JPM', 'KEY', 'LUK', 'LNC', 'L', 'MTB', 'MMC', 'MET', 'MCO', 'MS',\n",
    "           'NDAQ', 'NAVI', 'NTRS', 'PBCT', 'PNC', 'PFG', 'PGR', 'PRU', 'RJF', 'RF', 'SPGI', 'STT', 'STI', 'SYF', 'TROW',\n",
    "           'ABT', 'ABBV', 'AET', 'A', 'ALXN', 'ALGN', 'AGN', 'ABC', 'AMGN', 'ANTM', 'BCR', 'BAX', 'BDX', 'BIIB', 'BSX',\n",
    "           'BMY', 'CAH', 'CELG', 'CNC', 'CERN', 'CI', 'COO', 'DHR', 'DVA', 'XRAY', 'EW', 'EVHC', 'ESRX', 'GILD', 'HCA',\n",
    "           'HSIC', 'HOLX', 'HUM', 'IDXX', 'ILMN', 'INCY', 'ISRG', 'IQV', 'JNJ', 'LH', 'LLY', 'MCK', 'MDT', 'MRK', 'MTD',\n",
    "           'MYL', 'PDCO', 'PKI', 'PRGO', 'PFE', 'DGX', 'REGN', 'RMD', 'SYK', 'TMO', 'UNH', 'UHS', 'VAR', 'VRTX', 'WAT',\n",
    "           'MMM', 'AYI', 'ALK', 'ALLE', 'AAL', 'AME', 'AOS', 'ARNC', 'BA', 'CHRW', 'CAT', 'CTAS', 'CSX', 'CMI', 'DE',\n",
    "           'DAL', 'DOV', 'ETN', 'EMR', 'EFX', 'EXPD', 'FAST', 'FDX', 'FLS', 'FLR', 'FTV', 'FBHS', 'GD', 'GE', 'GWW',\n",
    "           'HON', 'INFO', 'ITW', 'IR', 'JEC', 'JBHT', 'JCI', 'KSU', 'LLL', 'LMT', 'MAS', 'NLSN', 'NSC', 'NOC', 'PCAR',\n",
    "           'PH', 'PNR', 'PWR', 'RTN', 'RSG', 'RHI', 'ROK', 'COL', 'ROP', 'LUV', 'SRCL', 'TXT', 'TDG', 'UNP', 'UAL',\n",
    "           'AES', 'LNT', 'AEE', 'AEP', 'AWK', 'CNP', 'CMS', 'ED', 'D', 'DTE', 'DUK', 'EIX', 'ETR', 'ES', 'EXC']"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## YFinance Download"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:55:06.273472Z",
     "start_time": "2021-04-19T18:54:56.262287Z"
    }
   },
   "source": [
    "import yfinance as yf\n",
    "import pandas_datareader.data as web\n",
    "yf.pdr_override()\n",
    "\n",
    "df = web.get_data_yahoo(tickers, start='2015-06-01',  end='2017-01-01')"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data Formatting"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:55:06.299710Z",
     "start_time": "2021-04-19T18:55:06.274655Z"
    }
   },
   "source": [
    "df = df.stack()\n",
    "df.index.names = ['date', 'asset']\n",
    "df = df.tz_localize('UTC', level='date')"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:55:06.308533Z",
     "start_time": "2021-04-19T18:55:06.300614Z"
    }
   },
   "source": [
    "df.info()"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Factor Computation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now it's time to build the events DataFrame, the input we will pass to Alphalens.\n",
    "\n",
    "Alphalens calculates statistics for those dates where the input DataFrame has values (not NaN). So to compute the performace analysis on specific dates and securities (like an event study) then we have to make sure the input DataFrame contains valid values only on those date/security combinations where the event happens. All the other values in the DataFrame must be NaN or not present.\n",
    "\n",
    "Also, make sure the event values are positive (it doesn't matter the value but they must be positive) if you intend to go long on the events and use negative values if you intent to go short. This impacts the cumulative returns plots. \n",
    "\n",
    "Let's create the event DataFrame where we \"mark\" (any value) each day a security price fall below 30$. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:55:06.332317Z",
     "start_time": "2021-04-19T18:55:06.309464Z"
    }
   },
   "source": [
    "today_price = df.loc[:, 'Open'].unstack('asset')\n",
    "yesterday_price = today_price.shift(1)\n",
    "events = today_price[(today_price < 30.0) & (yesterday_price >= 30)]\n",
    "events = events.stack()\n",
    "events = events.astype(float)\n",
    "events"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The pricing data passed to alphalens should contain the entry price for the assets so it must reflect the next available price after an event was observed at a given timestamp. Those prices must not be used in the calculation of the events for that time. Always double check to ensure you are not introducing lookahead bias to your study.\n",
    "\n",
    "The pricing data must also contain the exit price for the assets, for period 1 the price at the next timestamp will be used, for period 2 the price after 2 timestats will be used and so on.\n",
    "\n",
    "While Alphalens is time frequency agnostic, in our example we build 'pricing' DataFrame so that for each event timestamp it contains the assets open price for the next day afer the event is detected, this price will be used as the assets entry price. Also, we are not adding additional prices so the assets exit price will be the following days open prices (how many days depends on 'periods' argument)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:55:06.351638Z",
     "start_time": "2021-04-19T18:55:06.334334Z"
    }
   },
   "source": [
    "pricing = df.loc[:, 'Open'].iloc[1:].unstack('asset')"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:55:06.368177Z",
     "start_time": "2021-04-19T18:55:06.353103Z"
    }
   },
   "source": [
    "pricing.info()"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Run Event Study"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Configuration"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "Before running Alphalens beware of some important options: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:55:06.376011Z",
     "start_time": "2021-04-19T18:55:06.369474Z"
    }
   },
   "source": [
    "# we don't want any filtering to be done\n",
    "\n",
    "filter_zscore = None"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:55:06.383869Z",
     "start_time": "2021-04-19T18:55:06.377094Z"
    }
   },
   "source": [
    "# We want to have only one  bin/quantile. So we can either use quantiles=1 or bins=1\n",
    "\n",
    "quantiles = None\n",
    "bins = 1\n",
    "\n",
    "# Beware that in pandas versions below 0.20.0 there were few bugs in panda.qcut and pandas.cut\n",
    "# that resulted in ValueError exception to be thrown when identical values were present in the\n",
    "# dataframe and 1 quantile/bin was selected.\n",
    "# As a workaroung use the bins custom range option that include all your values. E.g.\n",
    "\n",
    "quantiles = None\n",
    "bins = [-1000000, 1000000]"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:55:06.392541Z",
     "start_time": "2021-04-19T18:55:06.384930Z"
    }
   },
   "source": [
    "# You don't have to directly set 'long_short' option when running alphalens.tears.create_event_study_tear_sheet\n",
    "# But in case you are making use of other Alphalens functions make sure to set 'long_short=False'\n",
    "# if you set 'long_short=True' Alphalens will perform forward return demeaning and that makes sense only\n",
    "# in a dollar neutral portfolio. With an event style signal you cannot usually create a dollar neutral\n",
    "# long/short portfolio\n",
    "\n",
    "long_short = False"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Get Alphalens Input"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:55:06.605891Z",
     "start_time": "2021-04-19T18:55:06.394261Z"
    }
   },
   "source": [
    "factor_data = alphalens.utils.get_clean_factor_and_forward_returns(events,\n",
    "                                                                   pricing,\n",
    "                                                                   quantiles=None,\n",
    "                                                                   bins=1,\n",
    "                                                                   periods=(\n",
    "                                                                       1, 2, 3, 4, 5, 6, 10),\n",
    "                                                                   filter_zscore=None)"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Run Event Tearsheet"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:55:09.176443Z",
     "start_time": "2021-04-19T18:55:06.606958Z"
    },
    "scrolled": false
   },
   "source": [
    "alphalens.tears.create_event_study_tear_sheet(\n",
    "    factor_data, pricing, avgretplot=(5, 10))"
   ],
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Short Signal Analysis"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If we wanted to analyze the performance of  short signal, we only had to switch from positive to negative event values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:55:09.179414Z",
     "start_time": "2021-04-19T18:55:09.177456Z"
    }
   },
   "source": [
    "events = -events"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:55:09.375636Z",
     "start_time": "2021-04-19T18:55:09.180310Z"
    }
   },
   "source": [
    "factor_data = alphalens.utils.get_clean_factor_and_forward_returns(events,\n",
    "                                                                   pricing,\n",
    "                                                                   quantiles=None,\n",
    "                                                                   bins=1,\n",
    "                                                                   periods=(\n",
    "                                                                       1, 2, 3, 4, 5, 6, 10),\n",
    "                                                                   filter_zscore=None)"
   ],
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-19T18:55:11.822514Z",
     "start_time": "2021-04-19T18:55:09.376640Z"
    }
   },
   "source": [
    "alphalens.tears.create_event_study_tear_sheet(\n",
    "    factor_data, pricing, avgretplot=(5, 10))"
   ],
   "outputs": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
